//发送模版消息
const axios = require('axios');
var Wechat = require('../wxTokenApi');
var { templateMesssage, templateMesssageNote } = require('./template');
const fs = require('fs');

module.exports = sendMessageModule = {
    //司机发送新小票消息
    async SendMsgToDriver(uesrMessage) {
        try {
            let wechat = new Wechat()
            let result_data = await wechat.fetchAccessToken()
            let access_token = result_data.access_token
            let message = templateMesssage(uesrMessage);
            let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`;
            let result = await axios({
                method: 'post',
                url: url,
                data: message
            })
            return result.data;
        } catch (error) {
            return '模板消息发送错误';
        }
    },
    readFileUserOpenId() {
        return new Promise((resolve, reject) => {
            fs.readFile(__dirname + '/userOpenId.txt', 'utf-8', function(err, data) {
                if (err) {
                    reject(err);
                } else {
                    data = JSON.parse(data);
                    resolve(data);
                }
            })
        })
    },
    //获取所有关注者用户Openid列表
    async GetAllUserOpenId() {
        let data = await this.readFileUserOpenId();
        let date = new Date();
        date = date.getTime();
        if (data.expiretime < date) {
            let wechat = new Wechat()
            let result_data = await wechat.fetchAccessToken()
            let access_token = result_data.access_token
            let url = `https://api.weixin.qq.com/cgi-bin/user/get?access_token=${access_token}`
            let result = await axios({
                method: 'get',
                url
            })
            result = result.data.data.openid
            let writeDate = date + 24 * 60 * 60 * 1000;
            let resultData = {
                expiretime: writeDate,
                data: result
            }
            resultData = JSON.stringify(resultData);
            fs.writeFile(__dirname + '/userOpenId.txt', resultData, (err) => {
                if (err) {
                    throw err;
                }
            })
            return JSON.parse(resultData);
        } else {
            return data;
        }
    },
    //给所有关注用户发送服务状态提醒消息
    async SendMsgToAll(Message) {
        try {
            let wechat = new Wechat()
            let result_data = await wechat.fetchAccessToken()
            let access_token = result_data.access_token
            let openidList = await this.GetAllUserOpenId();
            openidList = openidList.data;
            openidList.forEach(async function(item) {
                Message.openid = item;
                let message = templateMesssageNote(Message);
                let url = `https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=${access_token}`;
                let result = await axios({
                    method: 'post',
                    url: url,
                    data: message
                })
                return result.data;
            })

        } catch (error) {
            return '模板消息发送错误';
        }
    },
}





// sendMessageModule.SendMsgToAll({
//     'message': '受冷冷空气影响，港区风力较大，芜湖港暂停进提箱。计划于今天下午暂停提箱作业，恢复作业暂定今晚24点',
//     'servicename': '暂停空箱进提箱',
//     'time': '2022-1-11 16:38:50',
//     'note': '如有变化另行通知，请相互转告。不便之处，敬请谅解',
// }).then(value => {
//     console.log(value);
// })


























// const message = {
//         OpenId: 'oPBuf6haO1mR_ASkIFsWdLxobmSE',
//         DriverName: '王先生',
//         TruckLic: '皖BKFT903',
//         ContainerPlace: 'FUBAC2565',
//         ContainerID: '25648',
//         CreateTime: '2021-12-5 16:38:50',
//         CouponStatus: '是',
//         Receipt_Num: '686535'
//     }
// SendTempteMessage(message).then(value => {
//     console.log(value);
// });
/**
 * {
  total: 10,
  count: 10,
  data: {
    openid: [
      'oPBuf6oQnOyBASnsRTjOVqyQTiXw',
      'oPBuf6haO1mR_ASkIFsWdLxobmSE',
      'oPBuf6sYZcN2yEyg0mEgISh4RVng',
      'oPBuf6l5t45bLFgOSLzk-dAp1aQw',
      'oPBuf6pCMTbyR51B1W-vExTZhk3A',
      'oPBuf6n42qVTrjai46rCf7AtvO3Y',
      'oPBuf6vtztU8Ho28NAtDpAf2Sgkk',
      'oPBuf6guF2et9EnroRT2LlsxWhMY',
      'oPBuf6mflWi18UbNo6uaP4wPOaao',
      'oPBuf6kFDt8AUZuKzIeH2It9lajg'
    ]
  },
  next_openid: 'oPBuf6kFDt8AUZuKzIeH2It9lajg'
}
 */

/***
 * 
 * 
 * {
    "touser": "oPBuf6haO1mR_ASkIFsWdLxobmSE", 
    "url": "", 
    "template_id": "wXAVcQS04ox20WLRJRaBHdxYys0xvCBGzMrUDIVjSE8", 
    "topcolor": "#FF0000", 
    "data": {
        "message": {
            "value": "1", 
            "color": "#173177"
        }, 
        "servicename": {
            "value": "2", 
            "color": "#173177"
        }, 
        "time": {
            "value": "3", 
            "color": "#173177"
        }, 
        "note": {
            "value": "4", 
            "color": "#173177"
        }
    }
}
 */